package com.kingyea.mobilepolice.security;

import com.alibaba.fastjson.JSON;
import com.kingyea.mobilepolice.redis.service.RedisService;
import com.kingyea.mobilepolice.user.bean.User;
import com.kingyea.mobilepolice.util.GlobalVar;
import com.kingyea.mobilepolice.util.HttpContextHolderUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;

/**
 * 封装工具类 SecurityUtils
 */
@Component
public final class SecurityUtils {
    public final static String ROLE_ADMIN = "ROLE_ADMIN";

    //    @Autowired
//    private RedisTemplate redisTemplate;// 用户缓存信息是json，不是String
    private static final Logger logger = LoggerFactory.getLogger(SecurityUtils.class);

    //    @Autowired
//    private RedisTokenStore redisTokenStore;
    private static SecurityUtils securityUtils;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ConsumerTokenServices consumerTokenServices;

    /**
     * 获取当前用户名
     *
     * @return java.lang.String
     * @date 2018/3/19 14:02
     */
    public static String getCurrentUserUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = null;
        if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
            currentUserName = authentication.getName();
        }
        return currentUserName;
    }

    public static Boolean isAdmin() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication.getAuthorities().stream().filter(bean -> bean.getAuthority().equals(ROLE_ADMIN)).findFirst().isPresent();
    }

    /**
     * 获取当前用户
     *
     * @param
     * @return com.kingyea.mobilepolice.user.bean.User
     * @author Mr.Lin
     * @date 2018/4/10 13:55
     */
    public static User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User currentUser = null;
        if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken && !StringUtils.isEmpty(authentication.getName()))) {
            try {
                Object tokenObj = HttpContextHolderUtils.getToken();// 优先获取header里的token字段
                byte[] userJsonBytes = null;
                if (!StringUtils.isEmpty(tokenObj)) {
                    String userToken = tokenObj.toString();
                    String userJsonkey = GlobalVar.user_prefix + userToken;
                    userJsonBytes = securityUtils.redisService.get(null, (userJsonkey).getBytes());
                } else {
                    userJsonBytes = securityUtils.redisService.get(null, (GlobalVar.user_prefix + authentication.getName()).getBytes());
                }
                currentUser = JSON.parseObject(new String(userJsonBytes), User.class);
            } catch (Throwable e) {
                logger.error(e.getMessage());
            }

        }
        return currentUser;
    }

    public static boolean logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken && !StringUtils.isEmpty(authentication.getName()))) {
            try {
                Object tokenObj = HttpContextHolderUtils.getToken();// 优先获取header里的token字段
                String userToken = tokenObj.toString();
                String userJsonkey = GlobalVar.user_prefix + userToken;
                logger.info("【logout】" + userJsonkey);
                securityUtils.consumerTokenServices.revokeToken(tokenObj.toString());
                securityUtils.redisService.del(null, userJsonkey.getBytes());
                securityUtils.redisService.del(null, (GlobalVar.user_prefix + authentication.getName()).getBytes());
                SecurityContextHolder.getContext().setAuthentication(null);
                SecurityContextHolder.clearContext();
                return Boolean.TRUE;
            } catch (Throwable e) {
                logger.error("【logout】", e);
            }
        }
        return Boolean.FALSE;
    }

    @PostConstruct
    public void init() {
        securityUtils = this;
//        securityUtils.redisTemplate = this.redisTemplate;
        securityUtils.redisService = this.redisService;
//        securityUtils.redisTokenStore = this.redisTokenStore;
        securityUtils.consumerTokenServices = this.consumerTokenServices;
    }
}
